package com.example.openthedoor;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.openthedoor.databinding.RegisterFragmentBinding;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


public class RegisterFragment extends Fragment {
    private final int REQUEST_CAMERA = 110;
    private final int REQUEST_PICKER = 111;
    RegisterFragmentBinding binding;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
    BottomSheetDialog dialog;
    private MyViewModel myViewModel;
    private File photoFile = null;
    private String userName, passWord, userID;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        myViewModel = new ViewModelProvider(requireActivity()).get(MyViewModel.class);
        binding = DataBindingUtil.inflate(inflater, R.layout.register_fragment, container, false);
        binding.setData(myViewModel);

        Glide.with(requireContext())
                .load(R.drawable.ic_defualt_photo)
                .into(binding.imageViewPhoto);

        ListView listView = new ListView(getContext());
        listView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        String[] mode = {"摄像机", "图库", "取消"};
        listView.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, mode));

        dialog = new BottomSheetDialog(requireContext());
        dialog.setContentView(listView);

        binding.imageViewCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.show();
            }
        });

        listView.setOnItemClickListener((parent, view, position, id) -> {
            switch (position) {
                case 0:
                    // 摄像机的Intent
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    // 这个File 是用作保存拍照后的照片的,后面会将这个File设置为Intent的输出文件
                    photoFile = new File(getContext().getExternalCacheDir(), simpleDateFormat.format(new Date()) + ".png");
                    myViewModel.setPhoto(photoFile);
                    myViewModel.setPhotoPath(photoFile.getAbsolutePath());

                    // 将上面定义的file文件 转成合适的uri
                    Uri uri = FileProvider.getUriForFile(getContext(), "com.example.openthedoor.fileProvider", photoFile);
                    Log.e("myTag", "PhotoUri:" + uri);

                    // 将输出的文件uri 应用到intent中。
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

                    // 启动intent并等待返回值
                    startActivityForResult(intent, REQUEST_CAMERA);
                    break;
                case 1:
                    // 打开intent 隐式意图 相册
                    Intent intent1 = new Intent(Intent.ACTION_PICK);

                    // 设置需要的类型为图片
                    intent1.setType("image/*");

                    // 启动intent 并等待返回值
                    startActivityForResult(intent1, REQUEST_PICKER);
                    break;
                case 2:
                    dialog.dismiss();
                    break;
            }
        });

        binding.buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userName = binding.editTextName.getText().toString();
                passWord = binding.editTextPassword.getText().toString();
                userID = binding.editTextNumber.getText().toString();
                if (userName.isEmpty() || passWord.isEmpty() || userID.isEmpty() || myViewModel.getPhotoPath() == null) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
                    builder.setTitle("注册信息不完整！");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    AlertDialog dialog = builder.create();
                    dialog.show();
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
                    builder.setTitle("注册信息是否填写正确？");
                    builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //调用数据库 将用户名、学号、密码、图片传给数据库
                            myViewModel.register(userName, passWord, userID);
                            myViewModel.delay(300);
                            if (myViewModel.getSuccess()) {
                                //人脸注册
                                //myViewModel.init();
//                            try {
//                                myViewModel.faceRegister();
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
                                Toast.makeText(getContext(), "Success!", Toast.LENGTH_SHORT).show();
                                NavController controller = Navigation.findNavController(v);
                                controller.navigate(R.id.action_registerFragment_to_loginFragment);
                            } else {
                                Toast.makeText(getContext(), myViewModel.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                            }
                        });
                    builder.setNegativeButton("否",new DialogInterface.OnClickListener()

                        {
                            @Override
                            public void onClick (DialogInterface dialog,int which){

                        }
                        });
                        AlertDialog dialog = builder.create();
                    dialog.show();
                    }
                }

            });

        return binding.getRoot();
        }

        @Override
        public void onActivityResult ( int requestCode, int resultCode, @Nullable Intent data){
            super.onActivityResult(requestCode, resultCode, data);
            if (dialog != null) {
                dialog.dismiss();
            }
            if (requestCode == REQUEST_CAMERA && resultCode == -1) {
                Glide.with(getContext())
                        .load(photoFile)
                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                        .into(binding.imageViewPhoto);
            } else if (requestCode == REQUEST_PICKER) {
                Uri uri = null;
                // try 是有可能未选择图片就进行返回，会造成空指针
                try {
                    uri = data.getData(); //获取系统返回的照片uri
                } catch (NullPointerException e) {
                    e.printStackTrace();
                } finally {
                    if (uri != null) {
                        // 使用ContentResolve 进行读取选择的图片路径
                        String[] strings = {MediaStore.Images.Media.DATA};
                        Cursor cursor = getContext().getContentResolver().query(uri, strings, null, null, null);
                        cursor.moveToFirst();
                        int index = cursor.getColumnIndex(strings[0]);
                        String path = cursor.getString(index); //获取图片路径
                        myViewModel.setPhotoPath(path);
                        cursor.close();
                        Glide.with(getContext())
                                .load(path)
                                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                                .into(binding.imageViewPhoto);
                    }
                }
            }
        }
    }

